<template>
	<view class="content">
		
		<button @click="keepAlive" type="primary">开启后台保活</button>
		<button @click="isAddWhite" type="primary">是否已经开启电池优化</button>
<!-- 		<button @click="toWhiteListPage">android设置白名单(自启动、电池优化、锁屏清理、神隐模式等)</button>
		<button @click="hideSysTaskList">android隐藏app的任务栏</button> -->
		<text>{{curTime}}</text>
	</view>
</template>

<script>
	import {
		UTSKeepalive
	} from "@/uni_modules/wrs-uts-keepalive"
	let keepalive = new UTSKeepalive()


	export default {
		data() {
			let isAndroid = true
			switch (uni.getSystemInfoSync().platform) {
				case 'android': {
					isAndroid = true
				}
				break;
				case 'ios': {
					isAndroid = false

				}
				break
				default:
					break;
			}
			return {
				tel: "18024547319",
				isAndroid: isAndroid,
				title: 'Hello',
				curTime: null,
				count: 0,
				timer: null,
				msg: null
			}
		},
		onLoad() {
			// 设置回调
			UTSKeepalive.setCallback((resp)=>{
				this.showMsg(JSON.stringify(resp))
				let opt  = resp.opt 
				switch (opt){
					// 定位改变
					case "onLocationChanged":
					if(this.isAndroid) {
						let location = resp.location
						let latitude = location.latitude
						let longitude = location.longitude
						let speed = location.speed
					} else {
						let locations = resp.locations
					}
					   
						break;
					default:
						break;
				}
			})
			if (this.isAndroid) {
				this.requestPermission([
					"android.permission.FOREGROUND_SERVICE",
					"android.permission.POST_NOTIFICATIONS",
					"android.permission.ACCESS_COARSE_LOCATION",
					"android.permission.ACCESS_FINE_LOCATION",
					"android.permission.WRITE_EXTERNAL_STORAGE",
					"android.permission.ACCESS_BACKGROUND_LOCATION"
				])
			} else {
				var authorizationStatus = UTSKeepalive.getAuthorizationStatus();
				if (authorizationStatus == 0) {// 没有授权过定位时，请求定位权限
					keepalive.requestLocationAuthorization()
				}

				// 监听app前后台状态
				UTSKeepalive.listenerApp((resp) => {
					let opt = resp.opt
					switch (opt) {
						// app进入后台
						case "enterBackground": {
							var authorizationStatus = UTSKeepalive.getAuthorizationStatus();

							console.log("authorizationStatus:" + authorizationStatus)

							// app进入后台，此时采用定位保活还是采用播放音乐保活可以根据自己业务决定
							if (authorizationStatus == 3) { // 当定位权限是"总是一直"定位时采用定位来保活
								console.log("定位保活")
								keepalive.startLocation({
									desiredAccuracy: "NearestTenMeters",
									allowsBackgroundLocationUpdates: true, // 允许后台更新位置
									pausesLocationUpdatesAutomatically: false // 不允许自动暂停更新位置
								})
							} else { // 采用播放音乐保活
								console.log("播放音乐保活")
								UTSKeepalive.setCategory("playback")
								var url = plus.io.convertLocalFileSystemURL('_www/static/bgmusic.mp3');
		
								keepalive.playMusic({
									url: url,
									numberOfLoops: -1, // 循环此时，-1表示无限循环
									volume: 0 // 音量，0
								});
							}
							// 通知系统开始后台任务
							UTSKeepalive.beginBackgroundTask()
						}
						break;
						// app回到前台
						case "enterForeground": {
							// 停止播放音乐
							keepalive.stopMusic()
							// 停止定位
							keepalive.stopLocation()
							// 通知系统结束后台任务
							UTSKeepalive.endBackgroundTask()
						}

						break;
						default:
							break;
					}
				})
			}

		},
		onHide() {
			//页面消失的时候开启定时器实时刷新当前时间，app退到后台，app回到前台时，如果显示的是当前时间，说明后台保活有效，定时器在后台运行时一直有效
			// app后台运行时，观察控制台输出的定制日志
			if (this.timer) {
				clearInterval(this.timer);
			}

			this.timer = setInterval(() => {
				this.curTime = this.getCurrentTime()
				this.count = this.count + 1
				this.showMsg("定时任务 count: " + this.count)

			}, 1000);
		},
		onShow() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		},
		methods: {
			isAddWhite(){
				let flag = UTSKeepalive.isIgnoringBatteryOptimizations()
				if(flag) {
					this.showToast("电池没有优化次应用")
				} else {
					this.showToast("电池优化了次应用，请前往电池优化设置里关闭优化")
					
				}
			},
			hideSysTaskList() {
				if (this.isAndroid) {
					UTSKeepalive.hideSysTaskList()
				}
			},
			toWhiteListPage() {
				if (this.isAndroid) {
					UTSKeepalive.toWhiteListPage()
				}
			},
			getCurrentTime() {
				const date = new Date();
				const year = date.getFullYear();
				const month = ("0" + (date.getMonth() + 1)).slice(-2);
				const day = ("0" + date.getDate()).slice(-2);
				const hours = ("0" + date.getHours()).slice(-2);
				const minutes = ("0" + date.getMinutes()).slice(-2);
				const seconds = ("0" + date.getSeconds()).slice(-2);
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			keepAlive() {
				if (this.isAndroid) {
					let params = this.getAndroidNotification()
					UTSKeepalive.startForegroundService(params)
					
					UTSKeepalive.startJobService(params)
					UTSKeepalive.startLocalService(params)
					UTSKeepalive.startRemoteService(params)
					
					UTSKeepalive.startScreenLockReceiver()
					
					// 后台定位功能，用不到后台定位可以不需要调用
					// let fineLocationPermission = UTSKeepalive.checkSelfPermission("android.permission.ACCESS_FINE_LOCATION")
					// let coarseLocationPermission = UTSKeepalive.checkSelfPermission("android.permission.ACCESS_COARSE_LOCATION")
					// if(fineLocationPermission != 0 && coarseLocationPermission != 0) {
					// 	this.showToast("开启定位服务请先开启app定位权限")
					// } else {
					// 	let locationParams = {}
					// 	locationParams.notification = params
					// 	locationParams.location = {
					// 		provider: "gps", // 支持gps、fused、network、passive
					// 		minTimeMs: 500, // 间隔时间,这里为了测试效果，设置为500毫秒，实际情况根据自己业务设置
					// 		minDistanceM: 0.5 // 间隔距离,这里为了测试效果，设置为0.5米，实际情况根据自己业务设置
					// 	}
					// 	UTSKeepalive.startLocationService(locationParams)
					// }
				}

			},
			getAndroidNotification() {
				let channelId = 10
				let params = {}
				params.identifier = "123" // 通知ID，主要用于修改、删除通知，android里的identifier必须是数字，iOS的identifier可以是任意字符串
				params.channel = { // 如果已经channelId的channel则不创建，如果没有则会自动创建
					channelId: channelId,
					channelName: "保活channel",
					importance: 5, // 3: default 4: high 2: low 5: max 1: min 0: none
					lockscreenVisibility: 1, //1: public 0: private -1: secret
					description: "保活channel"
				}
				params.notification = {
					channelId: channelId, // 此消息通知是属于哪个channel的
					contentTitle: "保活通知",
					contentText: "保活",
					visibility: 1, // 1: public 0: private -1: secret
					smallIcon: { // 小图标，必传
						type: "resource", // 固定
						defType: "drawable", // 固定
						name: "not" // 文件名，不要带文件后缀，对应nativeResources/android/res/drawable文件夹下的图片
					},
					autoCancel: false,
					contentIntent: { // 设置点击通知要拉起的app
						intent: {
							className: "io.dcloud.PandoraEntry", // 设置拉起app的启动类名，uniapp的默认的本app类名是io.dcloud.PandoraEntry
							extra: { // 拉起app时的参数，一般用不到
								name: "张三",
								age: 14
							}
						}
					}
				}
				return params
			},
			requestPermission: function(permissions) {
				plus.android.requestPermissions(
					permissions,
					function(resultObj) {
						for (var i = 0; i < resultObj.granted.length; i++) {
							var grantedPermission = resultObj.granted[i];
							console.log('已获取的权限：' + grantedPermission);
						}
						for (var i = 0; i < resultObj.deniedPresent.length; i++) {
							var deniedPresentPermission = resultObj.deniedPresent[i];
							console.log('拒绝本次申请的权限：' + deniedPresentPermission);
						}
						for (var i = 0; i < resultObj.deniedAlways.length; i++) {
							var deniedAlwaysPermission = resultObj.deniedAlways[i];
							console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
						}
						// 若所需权限被永久拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限  
						if (resultObj.deniedAlways.length > 0) {
							// var Intent = plus.android.importClass("android.content.Intent");
							// var Settings = plus.android.importClass("android.provider.Settings");
							// var Uri = plus.android.importClass("android.net.Uri");
							// var mainActivity = plus.android.runtimeMainActivity();
							// var intent = new Intent();
							// intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							// var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
							// intent.setData(uri);
							// mainActivity.startActivity(intent);
						}
					},
					function(error) {
						console.log('申请权限错误：' + error.code + " = " + error.message);
					});
			},
			showModel: function(msg, confirmFun, cancelFun) {
				uni.showModal({
					title: '提示',
					content: msg,
					success: function(res) {
						if (res.confirm) {
							if (confirmFun) {
								confirmFun()
							}
						} else if (res.cancel) {
							if (confirmFun) {
								cancelFun()
							}
						}
					}
				});
			},
			showToast: function(msg) {
				uni.showToast({
					title: msg,
					duration: 2000
				});
			},
			showActionSheet: function(itemList, clickFun) {
				uni.showActionSheet({
					itemList: itemList,
					success: function(res) {
						if (clickFun) {
							clickFun(res.tapIndex);
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			clear() {
				this.msg = null
			},
			showMsg(info) {
				console.log(info)
				if (this.msg) {
					this.msg = this.msg + "\n" + info
				} else {
					this.msg = info
				}
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>